import _ from 'lodash';

const CheckValueModel = {
  namespace: 'dropViewState',
  state: {
    viewState: {},
  },
  effects: {},
  reducers: {
    changeCollapse(state, action) {
      const { nanoid, collapsed } = action.payload;
      return {
        ...state,
        viewState: {
          ...state.viewState,
          [nanoid]: { ...(state.viewState[nanoid] || {}), collapsed },
        },
      };
    },
    checkChange(state, action) {
      const { nanoid, item, status } = action.payload;
      const nextStateByNanoid = { ...(state.viewState[nanoid] || {}) };
      if (status) {
        nextStateByNanoid.checkedList = _.concat(
          nextStateByNanoid.checkedList || [],
          [item],
        );
      } else {
        const index = _.findIndex(
          nextStateByNanoid.checkedList,
          ({ id }) => id === item.id,
        );
        if (index > -1) {
          nextStateByNanoid.checkedList.splice(index, 1);
          nextStateByNanoid.checkedList = [...nextStateByNanoid.checkedList]; // ReactFC.memo use "===" to check equal
        }
      }
      const nextViewState = {
        ...state.viewState,
        [nanoid]: nextStateByNanoid,
      };

      return {
        ...state,
        viewState: nextViewState,
      };
    },
    clearChecked(state, action) {
      const { nanoid } = action.payload;
      return {
        ...state,
        viewState: {
          ...state.viewState,
          [nanoid]: { ...(state.viewState[nanoid] || {}), checkedList: [] },
        },
      };
    },
    clearStateByDelete(state, action) {
      const { nanoid } = action.payload;
      const nextViewState = { ...state.viewState };
      delete nextViewState[nanoid];
      return {
        ...state,
        viewState: nextViewState,
      };
    },
  },
};
export default CheckValueModel;
